import org.springframework.web.servlet.support.RequestContextUtils as RCU;

/**
 * Image Tag Library
 *
 * This library generic image tags for common features used
 * throughout the website:
 * <ul>
 * <li>image</li>
 * <li>favicon</li>
 * </ul>
 */
class ImageTagLib {
	/*
	 * Image Tag
	 *
	 * Builds a HTML img tag. Automatically determines the image width and
	 * height. Will specify the file name for name, alt and title if the
	 * optional parameters of "name" and "description" are not specified.
	 *
	 * Example: <g:image src="filename.jpg" name="" description="" />
	 */
	def image = { attributes ->

		//Declare variables
		java.awt.Image img;
		def output = "";
		def realPath;

		//Load locale and message properties file
 		def messageSource = grailsAttributes.
 			getApplicationContext().
 			getBean("messageSource");
		def locale = RCU.getLocale(request);

		//Source
		if (attributes['src'] != null) {
			output += """<img src="${grailsAttributes.getApplicationUri(request)}""" +
				"""/images/${attributes['src']}" """;
		} else {
			throwTagError("Tag [image] is missing required attribute [src]");
		}

		//Validate source
		try {
			realPath = grailsAttributes.getServletContext().getRealPath("images/${attributes['src']}");
			img = javax.imageio.ImageIO.read(new java.io.File(realPath));
			if(img != null) {
				output += """width="${img.getWidth()}" height="${img.getHeight()}" """;
			}
		} catch(Exception ex) {
			log.error("Tag [image] is unable to open the specified image file [${realPath}]");
			out << "";
		}

		//Name attribute
		if (attributes['name'] != null) {
            //Get message value
			def name = messageSource.getMessage(
					attributes['name'],
					null,
					null,
					locale
			);

			//Store name
			if(name != null) {
				output += """name="${name}" """;
			} else {
				output += """name="${attributes['name']}" """;
			}
		} else {
			//Use filename
			if(realPath.lastIndexOf('\\') > 0) {
				realPath = realPath.substring(realPath.lastIndexOf('\\')+1, realPath.length());
			} else if(realPath.lastIndexOf('/') > 0) {
				realPath = realPath.substring(realPath.lastIndexOf('/')+1, realPath.length());
			}

			//Store name
			output += """name="${realPath}" """;
		}

		//Text attributes
		if (attributes['description'] != null) {
            //Get message value
			def message = messageSource.getMessage(
					attributes['description'],
					null,
					null,
					locale
			);

			//Store message value as the alt and title attributes
			if(message != null) {
				output += """alt="${message}" title="${message}" """;
			} else {
				output += """alt="${attributes['description']}" title="${attributes['description']}" """;
			}
		} else {
			//Use filename
			if(realPath.lastIndexOf('\\') > 0) {
				realPath = realPath.substring(realPath.lastIndexOf('\\')+1, realPath.length());
			} else if(realPath.lastIndexOf('/') > 0) {
				realPath = realPath.substring(realPath.lastIndexOf('/')+1, realPath.length());
			}

			//Store name
			output += """alt="${realPath}" title="${realPath}" """;
		}

		//Output
		if(img != null) {
			output += "/>";
			out << output;
		}
	}

	/*
	 * Favicon Tag
	 *
	 * Builds a favicon shortcut icon link. Detects that the css
	 * file actually exists and then outputs a valid css link.
	 *
	 * Example: <g:favicon src="favicon.ico" />
	 */
	def favicon = { attributes ->

		//Declare variables
		def output;
		def realPath;
		def io;

		//Source
		if (attributes['src'] != null) {
			output = """<link rel="shortcut icon" href="${grailsAttributes.getApplicationUri(request)}""" +
				"""/images/${attributes['src']}" type="image/x-icon" />""";
		} else {
			throwTagError("Tag [favicon] is missing required attribute [src]");
		}

		//Validate source
		realPath = grailsAttributes.getServletContext().getRealPath("images/${attributes['src']}");
		if(realPath != null) {
			io = new java.io.File(realPath);
			if(io.exists() && io.isFile()) {
				out << output;
			} else {
				log.error("Tag [favicon] is unable to find the specified favicon file [${realPath}]");
				out << "";
			}
		} else {
			log.error("Tag [favicon] is unable to find the specified favicon file []");
			out << "";
		}
	}
}